package com.module.aichat.data.protocol

import android.util.Log
import com.beust.klaxon.Klaxon
import com.common.app.helper.UserHelper
import com.module.aichat.data.bean.MsgDirection
import com.module.aichat.db.table.DBMessage

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/6/30
 * <p>
 * 描述：消息转换的工厂类,将协议消息体封装为本地消息体
 * <p>
 * 修订历史：
 */
object MessageConvertFactory {

    /**
     * 将协议消息体封装为本地消息体
     */
    fun convertMessage2DBMessage(json: String): DBMessage? {
        var dbMessage: DBMessage? = null
        kotlin.runCatching {
            Log.e("SOSOU---MessageConvertFactory-----", "开始解析")
            //协议消息对象
            val message = Klaxon().parse<Message>(json)
            //将协议对象消息封装成本地的数据库消息对象
            dbMessage = DBMessage().apply {
                type = message?.type ?: ""
                version = message?.version ?: ""
                sendTime = message?.sendTime ?: 0L
                id = message?.id ?: ""
                targetId = message?.targetId ?: ""
                senderId = message?.senderId ?: ""
                extra = message?.extra ?: ""
                content = message?.content
                //这一步赋值不能丢，丢了在进行json转换的时候会出错
                content?.type = type ?: ""
                //标记消息的方向
                msgDirection = if (senderId == UserHelper.getUid()) MsgDirection.SEND else MsgDirection.RECEIVE
                sendStatus = message?.sendStatus?:0

                //赋值targetID
                targetId = message?.targetId

                needToInsertDB = content?.needToInsertDB() ?: false
            }
        }.onFailure {
            return null
        }
        return dbMessage
    }
}